"""
数据库初始化脚本
"""
import os
import sys

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app import app, db
from models import TestCase, TestSuite

def init_db():
    """初始化数据库"""
    with app.app_context():
        try:
            # 创建所有表
            db.create_all()
            
            # 更新现有数据的is_deleted字段为False（如果没有设置的话）
            # 这样可以确保添加逻辑删除字段后，现有数据仍然可见
            test_cases_updated = TestCase.query.filter(TestCase.is_deleted.is_(None)).update({TestCase.is_deleted: False})
            test_suites_updated = TestSuite.query.filter(TestSuite.is_deleted.is_(None)).update({TestSuite.is_deleted: False})
            
            # 同时更新is_deleted为True的记录为False，确保现有数据可见
            test_cases_updated += TestCase.query.filter(TestCase.is_deleted == True).update({TestCase.is_deleted: False})
            test_suites_updated += TestSuite.query.filter(TestSuite.is_deleted == True).update({TestSuite.is_deleted: False})
            
            if test_cases_updated > 0 or test_suites_updated > 0:
                db.session.commit()
                print(f"更新了 {test_cases_updated} 个测试用例和 {test_suites_updated} 个测试套件的删除状态")
            
            print("数据库表创建成功")
            return True
        except Exception as e:
            print(f"数据库初始化失败: {e}")
            return False

if __name__ == '__main__':
    print("正在初始化数据库...")
    if init_db():
        print("数据库初始化完成")
    else:
        print("数据库初始化失败")